package com.saas.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import sun.misc.BASE64Decoder;

public class FileUtil {

	// TODO: Get parameters from property.
	public static final List<String> TYPE_OF_PICTURE_LIST = new ArrayList<String>(Arrays.asList("jpg", "png", "gif", "jpeg"));

	private static Logger logger = Logger.getLogger(FileUtil.class);

	/**
	 * A tool 4 saving stuff, 4 any file type, in Base64.
	 * 
	 * @author Aries
	 * @param path
	 *            fileName file
	 * @return String
	 */
	public static String saveBase64(String path, String fileName, String base64File) {
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] bytes = decoder.decodeBuffer(base64File);
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {
					bytes[i] += 256;// 调整异常数据
				}
			}
			new File(path).mkdirs();
			OutputStream outs = new FileOutputStream(path + "/" + fileName);
			outs.write(bytes);
			outs.flush();
			outs.close();
			return path + "/" + fileName;
		} catch (Exception e) {
			logger.error("Save file failed by saveBase64-function in FileReceiverUtil.java");
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * A tool 4 saving stuff, 4 any file type, in file.
	 * 
	 * @author Aries
	 * @param userid
	 *            path fileName file
	 * @return String
	 */
	public static String saveFile(String userid, String path, String fileName, File file) {
		File target = new File(path, fileName);
		try {
			FileUtils.copyFile(file, target);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error("Save file failed by saveFile-function in FileReceiverUtil.java");
			e.printStackTrace();
			return null;
		}
		return path + "/" + fileName;
	}

	/**
	 * Format current time 4 file name.
	 * 
	 * @author Aries
	 * @param template
	 * @return String
	 */
	public static String getFormatedTime(String template) {
		return new SimpleDateFormat(template).format(new Date());
	}

	/**
	 * Generate extension, Only 4 file transport.
	 * 
	 * @author Aries
	 * @param fileName
	 * @return extension
	 */
	public static String getExtenedFileName(String fileName) {
		int position = fileName.lastIndexOf(".");
		String extension = fileName.substring(position);
		return extension;
	}

	/**
	 * A tool 4 picture validation
	 * 
	 * @author Aries
	 * @param extension
	 * @return boolean
	 */
	public static boolean isPicture(String extension) {
		if(StringUtils.isEmpty(extension)){
			return false;
		}
		return TYPE_OF_PICTURE_LIST.contains(extension.toLowerCase());
	}
}
